//
//  FRHttpRequest.m
//  FastRunning
//
//  Created by HUA on 2018/4/12.
//  Copyright © 2018年 HUA. All rights reserved.
//

#import "FRHttpRequest.h"
#import "AFNetworking.h"
#import "FRUrls.h"

@interface FRHttpRequest ()
@property (nonatomic, strong)  AFHTTPSessionManager *manager ;
@end

//超时时间
const float timeoutInterval = 45.00;

@implementation FRHttpRequest

+ (instancetype) shareHttpRequest {
    static FRHttpRequest *httpRequest = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpRequest = [[FRHttpRequest alloc] init];
    });
    
    return httpRequest;
}

- (void)requestWithRequestType:(FRHttpRequestType)requestType URLString:(NSString *)URLString parameters:(id)parameters progress:(void (^)(NSProgress *))progress success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict = parameters;
    URLString = [NSString stringWithFormat:@"%@%@",Domain,URLString];
    
    if (requestType == FRHttpRequestTypePOST) {
        [_manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            if (progress) {
                progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"请求成功:%@",responseObject);
            if (success) {
                success(task,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败:%@",error);
            if (failure) {
                failure(task,error);
            }
        }];
    } else if (requestType == FRHttpRequestTypeGET) {
        [_manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            if (progress) {
                progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"请求成功:%@",responseObject);
            if (success) {
                success(task,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败:%@",error);
            if (failure) {
                failure(task,error);
            }
        }];
    }
}

//取消所有请求
- (void)cancelAllOperations {
    if (self.manager) {
        [self.manager.operationQueue cancelAllOperations];
    }
}

#pragma Mark - setter && getter
- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.requestSerializer.timeoutInterval = timeoutInterval;
        _manager.responseSerializer.acceptableContentTypes = [_manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    }
    return _manager;
}



@end
